package cn.iune.erp.payment;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.justep.baas.Utils;

import cn.iune.common.response.MapMessage;
import cn.iune.erp.customer.FileCustomer;
import cn.iune.erp.customer.IFileCustomerService;
import cn.iune.erp.customer.IMemberPointsService;
import cn.iune.erp.invoice.AccountInvoice;
import cn.iune.erp.invoice.IAccountInvoiceService;
import cn.iune.erp.provider.FileProvider;
import cn.iune.erp.provider.IFileProviderService;
import cn.iune.erp.sale.SaleOrder;
import cn.iune.erp.setting.ISettingService;

@Transactional
@Service

public class PaymentServiceImpl implements IPaymentService {

	
	@Autowired
	private IAccountPaymentService accountPaymentService;
	@Autowired
	private IAccountPaymentDetailService accountPaymentDetailService;

	@Autowired
	private IFileCustomerService fileCustomerService;
	@Autowired
	private IAccountInvoiceService accountInvoiceService;
	
	@Autowired
	private IMemberPointsService memberPointsService;

	@Autowired
	private IFileProviderService fileProviderService;
	
	@Autowired
	private ISettingService settingService;


	
	
	@Transactional
	private int doItPayment(AccountPayment obj) {

		//////////////////////////////////主表（单据表）//////////////////////////////	
		//收付款单审核

		//收付款单主表
		
		if(obj.getBillType().equals("SKDJ") || obj.getBillType().equals("FKDJ") || obj.getBillType().equals("STDJ") || obj.getBillType().equals("FTDJ")){
			//核销表中插入主表（收付款表）的核销记录
			String writeOffNo = obj.getAccountPaymentNo();
			
			String revOpay = obj.getRevOpay();
			int direction = obj.getDirection();
			
			String clearType = null;
			String clearTypeLabel = null;
			if(obj.getBillType().equals("SKDJ")) {
				clearType = "6";
				clearTypeLabel = "6.到款核销";
			}
			if(obj.getBillType().equals("FKDJ")) {
				clearType = "6";
				clearTypeLabel = "6.付款核销";
			}
			if(obj.getBillType().equals("STDJ") || obj.getBillType().equals("FTDJ")) {
				clearType = "D";
				clearTypeLabel = "D.退款核销";
			}
				
			String billType = "3";//obj.getBillType();// "SKDJ";
			String billTypeName = "3."+obj.getBillTypeName();// "收款单据";
			
			int cashSettle = obj.getCashSettle();
			
			String origin = obj.getBillType();
			String originName = obj.getBillTypeName();
			String originNo = obj.getAccountPaymentNo();
			
			String dealObject = obj.getDealObject();
			String dealObjectLabel = obj.getDealObjectLabel();
			String customerID = obj.getCustomerID();
			String customerNo = obj.getCustomerNo();
			String shortName = obj.getShortName();
			String customerName = obj.getCustomerName();
			
			String cUsercode = obj.getcUsercode();
			String cUsername = obj.getcUsername();
			String userId = obj.getUserId();
			String employeeNo = obj.getEmployeeNo();
			String employeeName = obj.getEmployeeName();
			String enterpriseNo = obj.getEnterpriseNo();
			String enterpriseName = obj.getEnterpriseName();
			
			String captionID = null;
			String captionNo = null;
			String captionName = null;
			String captionFullName = null;
			
			accountPaymentDetailService.accountPaymentDetailDKHXInsert(writeOffNo, cashSettle, revOpay, direction, clearType, clearTypeLabel, billType, billTypeName, origin, originName, originNo, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, obj.getOrderAmount(), captionID, captionNo, captionName, captionFullName, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);

			//核销表中插入主表的现金折扣
			BigDecimal discountCashTotal = obj.getDiscountCash();
			if(discountCashTotal.compareTo(BigDecimal.ZERO)>0) {
				//////////////////////////////////////////////////////////////////////////////
				if(obj.getBillType().equals("SKDJ")){
					billType = "5";
					billTypeName = "5.收款核销折扣";
				}
				if(obj.getBillType().equals("FKDJ")){
					billType = "5.";
					billTypeName = "5.付款核销折扣";
				}
				accountPaymentDetailService.accountPaymentDetailDKHXInsert(writeOffNo, cashSettle, revOpay, direction, clearType, clearTypeLabel, billType, billTypeName, origin, originName, originNo, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, discountCashTotal, captionID, captionNo, captionName, captionFullName, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
				//////////////////////////////////////////////////////////////////////////////
			}
			
			obj.setHandling("cleared");
			obj.setHandlingLabel("已核销");
			accountPaymentService.update(obj);
		}	
		
		
		
		//实收//////////////////////////////////////////////////////////
		//预收款单核销（预收款单放在主表中）
		if (obj.getBillType().equals("YSKD")){
			//会员充值余额被核销
//			if("Y".equals(obj.getClearType())) {
//				String customerID = obj.getCustomerID();
//				fileCustomerService.updateMemberAmount(customerID, obj.getOrderAmountTotal());
//			}
			
			//不在此关联处理，进行单独处理
//			if("XSDD".equals(obj.getOrigin()) && null!=obj.getOriginNo() && !"".equals(obj.getOriginNo())){
//				if(obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())){
//					saleOrderService.pay(obj.getOriginNo(), obj.getEnterpriseNo());
//				}
//			}
			

		}

		//收款单主表
		if(obj.getBillType().equals("SKDJ") || obj.getBillType().equals("STDJ")){
			
			//更新累计消费金额
			/*
			if("cus".equals(obj.getDealObject()) && obj.getCustomerID()!=null){
				fileCustomerService.updateTotalAmount(obj.getCustomerID(), obj.getAccountAmountTotal());
			}
			*/
			//更新客户积分
			/*
			if("cus".equals(obj.getDealObject()) && obj.getCustomerID()!=null){
				fileCustomerService.updateMemberPoints(obj.getCustomerID(), obj.getAccountActual());
			}
			*/
//			String dealObject = obj.getDealObject();
//			String dealObjectLabel = obj.getDealObjectLabel();
//			String customerID = obj.getCustomerID();
//			String customerNo = obj.getCustomerNo();
//			String shortName = obj.getShortName();
//			String customerName = obj.getCustomerName();
//			BigDecimal memberPoints = obj.getAccountAmountTotal();
//			String comments = "付款完成获得积分，1元等于1积分。";
//			String cUsercode = obj.getcUsercode();
//			String cUsername = obj.getcUsername();
//			String userId = obj.getUserId();
//			String enterpriseNo = obj.getEnterpriseNo();
//			String enterpriseName = obj.getEnterpriseName();
//			memberPointsService.insert(dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, memberPoints, comments, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
		}
		
		
		
		//实付////////////////////////
		
		
		
		//预付款单核销（预收款单放在主表中）
		/*
		if (obj.getBillType().equals("YFKD") && "3".equals(obj.getClearType())){
			if("CGDD".equals(obj.getOrigin()) && null!=obj.getOriginNo() && !"".equals(obj.getOriginNo())){
				//如果数据来源是销售发票，则更新核销金额
				if(obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())){
					purchaseOrderService.updatePredictAmount(obj.getOriginNo(), obj.getEnterpriseNo(), obj.getAccountAmountTotal());
				}
			}
		}
		*/
		
		
		
		/*
		//登记资金帐户
		//判断单据为实收
		if (obj.getBillType().equals("SKDJ") || obj.getBillType().equals("YSKD")){
			if(obj.getCapitalFullNo()!=null  && !"".equals(obj.getCapitalFullNo())){
				//登记资金帐户
				AccountCaptionUtil acu = new AccountCaptionUtil();
				if(acu!=null){
					acu.storeRegister(obj.getCapitalFullNo(),obj.getAccountActual(),obj.getEnterpriseNo());
				}
			}

		}
		//判断单据为实付
		if (obj.getBillType().equals("FKDJ") || obj.getBillType().equals("YFKD") ){
			if(obj.getCapitalFullNo()!=null  && !"".equals(obj.getCapitalFullNo())){
				//登记资金帐户
				AccountCaptionUtil acu = new AccountCaptionUtil();
				if(acu!=null){
					acu.storeRegister(obj.getCapitalFullNo(),obj.getAccountActual(),obj.getEnterpriseNo());
				}
			}

		}
		*/
		////////////////////////////////////////////////////////////////////////////////////////////
		
		
		return 0;

	}
	
	@Transactional
	private int unDoPayment(AccountPayment obj) {

		//////////////////////////////////主表（单据表）//////////////////////////////	
		//收付款单审核

		
		//收款单主表
		if(obj.getBillType().equals("SKDJ") || obj.getBillType().equals("FKDJ") || obj.getBillType().equals("STDJ") || obj.getBillType().equals("FTDJ")){
			//删除核销记录到从表中
			String writeOffNo = obj.getAccountPaymentNo();
			String enterpriseNo = obj.getEnterpriseNo();
			String billType = "3";//obj.getBillType();
			String originNo = obj.getAccountPaymentNo();
			accountPaymentDetailService.accountPaymentDetailDKHXDelete(writeOffNo, billType, originNo, enterpriseNo);

			BigDecimal discountCashTotal = obj.getDiscountCash();
			if(discountCashTotal.compareTo(BigDecimal.ZERO)>0) {
				
				//////////////////////////////////////////////////////////////////////////////
				if(obj.getBillType().equals("SKDJ")){
					billType = "5";
				}
				if(obj.getBillType().equals("FKDJ")){
					billType = "5";
				}
				accountPaymentDetailService.accountPaymentDetailDKHXDelete(writeOffNo, billType, originNo, enterpriseNo);
				//////////////////////////////////////////////////////////////////////////////
			}
			
			obj.setHandling("unclear");
			obj.setHandlingLabel("未核销");
			accountPaymentService.update(obj);
		}	
		
		

		//实收//////////////////////////////////////////////////////////
		//预收款单核销（预收款单放在主表中）
		if (obj.getBillType().equals("YSKD")){
			//会员充值余额被核销
//			if("Y".equals(obj.getClearType())) {
//				String customerID = obj.getCustomerID();
//				fileCustomerService.updateMemberAmount(customerID, obj.getOrderAmountTotal().negate());
//			}
			
			//不在此关联处理，进行单独处理
//			if("XSDD".equals(obj.getOrigin()) && null!=obj.getOriginNo() && !"".equals(obj.getOriginNo())){
//				if(obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())){
//					saleOrderService.unpay(obj.getOriginNo(), obj.getEnterpriseNo());
//				}
//			}
			
		}

		//收款单主表
		if(obj.getBillType().equals("SKDJ") || obj.getBillType().equals("STDJ")){
			
			//更新累计消费金额
			/*
			if("cus".equals(obj.getDealObject()) && obj.getCustomerID()!=null){
				fileCustomerService.updateTotalAmount(obj.getCustomerID(), obj.getAccountAmountTotal().negate());
			}
			*/
			/*
			//更新客户积分
			if("cus".equals(obj.getDealObject()) && obj.getCustomerID()!=null){
				fileCustomerService.updateMemberPoints(obj.getCustomerID(), obj.getAccountActual().negate());
			}
			*/
//			String dealObject = obj.getDealObject();
//			String dealObjectLabel = obj.getDealObjectLabel();
//			String customerID = obj.getCustomerID();
//			String customerNo = obj.getCustomerNo();
//			String shortName = obj.getShortName();
//			String customerName = obj.getCustomerName();
//			BigDecimal memberPoints = obj.getAccountAmountTotal().negate();
//			String comments = "付款撤销获得积分，1元等于1积分。";
//			String cUsercode = obj.getcUsercode();
//			String cUsername = obj.getcUsername();
//			String userId = obj.getUserId();
//			String enterpriseNo = obj.getEnterpriseNo();
//			String enterpriseName = obj.getEnterpriseName();
//			memberPointsService.insert(dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, memberPoints, comments, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
		}
		
		//预付款单核销（预收款单放在主表中）
		/*
		if (obj.getBillType().equals("YFKD") && "3".equals(obj.getClearType())){
			if("CGDD".equals(obj.getOrigin()) && null!=obj.getOriginNo() && !"".equals(obj.getOriginNo())){
				//如果数据来源是销售发票，则更新核销金额
				if(obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())){
					purchaseOrderService.updatePredictAmount(obj.getOriginNo(), obj.getEnterpriseNo(), obj.getAccountAmountTotal().negate());
				}
			}
		}
		*/
		
		/*
		//登记资金帐户
		//判断单据为实收
		if (obj.getBillType().equals("SKDJ") || obj.getBillType().equals("YSKD")){
			if(obj.getCapitalFullNo()!=null  && !"".equals(obj.getCapitalFullNo())){
				//登记资金帐户
				AccountCaptionUtil acu = new AccountCaptionUtil();
				if(acu!=null){
					acu.storeRegister(obj.getCapitalFullNo(),obj.getAccountActual().negate(),obj.getEnterpriseNo());
				}
			}
		}
		//判断单据为实付
		if (obj.getBillType().equals("FKDJ") || obj.getBillType().equals("YFKD") 
				){
			if(obj.getCapitalFullNo()!=null  && !"".equals(obj.getCapitalFullNo())){
				//登记资金帐户
				AccountCaptionUtil acu = new AccountCaptionUtil();
				if(acu!=null){
					acu.storeRegister(obj.getCapitalFullNo(),obj.getAccountActual().negate(),obj.getEnterpriseNo());
				}
			}
		}
		*/
		////////////////////////////////////////////////////////////////////////////////////////////
		

		return 0;
	}
	
	@Transactional
	private int doItPaymentDetail(AccountPaymentDetail obj) {

		///////////////////////////////子表（核销表）/////////////////////////////////
		
		//应收核销
		if((obj.getOrigin().equals("XSFP")) || (obj.getOrigin().equals("QTYS"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				accountInvoiceService.orderAmountClearedAdd(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs(),obj.getDiscountCash());
			}
		}
		
		//收款单和退款单明细核销
		//核销预收款单
		if((obj.getOrigin().equals("YSKD"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//如果数据来源是销售发票，则更新核销金额
				accountPaymentService.updateYSKDClearedAmount(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs());
				
				//更新客户积分
				String dealObject = obj.getDealObject();
				String dealObjectLabel = obj.getDealObjectLabel();
				String customerID = obj.getCustomerID();
				String customerNo = obj.getCustomerNo();
				String shortName = obj.getShortName();
				String customerName = obj.getCustomerName();
				BigDecimal memberPoints = obj.getOrderAmountCleared().abs();
				String comments = "预付款核销完成获得积分，1元等于1积分。";
				
				String cUsercode = obj.getcUsercode();
				String cUsername = obj.getcUsername();
				String userId = obj.getUserId();
				String enterpriseNo = obj.getEnterpriseNo();
				String enterpriseName = obj.getEnterpriseName();
				
				memberPointsService.insert(dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, memberPoints, comments, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
			}
			//会员充值余额被核销
			if("Y".equals(obj.getBillType())) {
				String customerID = obj.getCustomerID();
				fileCustomerService.updateMemberAmount(customerID, obj.getOrderAmountCleared());
			}
		}
		//核销预收款单--代金券
		if((obj.getOrigin().equals("RDJQ"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//如果数据来源是销售发票，则更新核销金额
				accountPaymentService.updateRDJQClearedAmount(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs());
			}
		}
		
		//付款单核销//付款核销单
		if((obj.getOrigin().equals("CGFP")) || (obj.getOrigin().equals("QTYF"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//如果数据来源是采购发票，则更新核销金额
				accountInvoiceService.orderAmountClearedAdd(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs(),obj.getDiscountCash());
			}

		}
		
		//核销预付款单
		if((obj.getOrigin().equals("YFKD"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//如果数据来源是销售发票，则更新核销金额
				accountPaymentService.updateYFKDClearedAmount(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs());
			}
		}


		///////////////////////////////////////////////////////////////////////////////////////
		
		return 0;

	}
	
	@Transactional
	private int unDoPaymentDetail(AccountPaymentDetail obj) {

		///////////////////////////////子表（核销表）/////////////////////////////////

		
		//应收核销
		if((obj.getOrigin().equals("XSFP")) || (obj.getOrigin().equals("QTYS"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				accountInvoiceService.orderAmountClearedSub(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs(),obj.getDiscountCash());
			}

		}
		
		//收款单和退款单明细核销
		//核销预收款单
		if((obj.getOrigin().equals("YSKD"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//如果数据来源是销售发票，则更新核销金额
				accountPaymentService.updateYSKDClearedAmount(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs().negate());

				//更新客户积分
				String dealObject = obj.getDealObject();
				String dealObjectLabel = obj.getDealObjectLabel();
				String customerID = obj.getCustomerID();
				String customerNo = obj.getCustomerNo();
				String shortName = obj.getShortName();
				String customerName = obj.getCustomerName();
				BigDecimal memberPoints = obj.getOrderAmountCleared().abs().negate();
				String comments = "预付款核销撤销获得积分，1元等于1积分。";
				
				String cUsercode = obj.getcUsercode();
				String cUsername = obj.getcUsername();
				String userId = obj.getUserId();
				String enterpriseNo = obj.getEnterpriseNo();
				String enterpriseName = obj.getEnterpriseName();
				
				memberPointsService.insert(dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, memberPoints, comments, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
				
			}
			//会员充值余额被核销
			if("Y".equals(obj.getBillType())) {
				String customerID = obj.getCustomerID();
				fileCustomerService.updateMemberAmount(customerID, obj.getOrderAmountCleared().negate());
			}

		}
		
		//核销预收款单--代金券
		if((obj.getOrigin().equals("RDJQ"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//如果数据来源是销售发票，则更新核销金额
				accountPaymentService.updateRDJQClearedAmount(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs().negate());
			}
		}
		
		//付款单核销//付款核销单
		if((obj.getOrigin().equals("CGFP")) || (obj.getOrigin().equals("QTYF"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//如果数据来源是采购发票，则更新核销金额
				accountInvoiceService.orderAmountClearedSub(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs(),obj.getDiscountCash());
			}

		}
		
		//核销预付款单
		if((obj.getOrigin().equals("YFKD"))){
			if (obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//如果数据来源是销售发票，则更新核销金额
				accountPaymentService.updateYFKDClearedAmount(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountCleared().abs().negate());
			}
		}


		///////////////////////////////////////////////////////////////////////////////

		return 0;
	}
	
	@Transactional
	@Override
    public void afterInsertPayment(AccountPayment obj){
		
		//收款核销单
		/*
		if(obj.getBillType().equals("SKHX")){
			if (obj.getOrigin().equals("YSKD")) {
				//如果数据来源是销售发票，则更新核销金额
				this.updateOrderAmountCleareding(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountTotal());
			}
		}
		
		//付款核销单
		if(obj.getBillType().equals("FKHX")){
			if (obj.getOrigin().equals("YFKD")){
				//如果数据来源是采购发票，则更新核销金额
				this.updateOrderAmountCleareding(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountTotal());
			}
		}
		*/
		
		//处理现结收款单
		/*
		if(obj.getBillType().equals("SKDJ") && "Y".equals(obj.getAutoPayment())){
			if ("XSFP".equals(obj.getOrigin()) && obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//
				String autoPayment, next, nextName, nextNo;
				autoPayment = obj.getAutoPayment();
				next = obj.getBillType();
				nextName = obj.getBillTypeName();
				nextNo = obj.getAccountPaymentNo();
				accountPaymentService.updateNextNo(obj.getOriginNo(),obj.getEnterpriseNo(), autoPayment, next, nextName, nextNo, obj.getSettleCategory(), obj.getSettleCategoryLabel());
			}
		}
		*/

	}
	
	@Transactional
	@Override
    public void beforeDeletePayment(String fID){
//		AccountPayment obj = accountPaymentService.getByID(fID);
		
		/*
		//收款核销单
		if(obj.getBillType().equals("SKHX")){
			if (obj.getOrigin().equals("YSKD")) {
				//如果数据来源是销售发票，则更新核销金额
				this.updateOrderAmountCleareding(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountTotal().negate());
			}
		}
		
		//付款核销单
		if(obj.getBillType().equals("FKHX")){
			if (obj.getOrigin().equals("YFKD")){
				//如果数据来源是采购发票，则更新核销金额
				this.updateOrderAmountCleareding(obj.getOriginNo(),obj.getEnterpriseNo(),obj.getOrderAmountTotal().negate());
			}
		}
		*/
		
		//处理现结收款单
		/*
		if(obj.getBillType().equals("SKDJ") && "Y".equals(obj.getAutoPayment())){
			if ("XSFP".equals(obj.getOrigin()) && obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				String autoPayment, next, nextName, nextNo;
				autoPayment = null;
				next = null;
				nextName = null;
				nextNo = null;
				accountPaymentService.updateNextNo(obj.getOriginNo(),obj.getEnterpriseNo(), autoPayment, next, nextName, nextNo, obj.getSettleCategory(), obj.getSettleCategoryLabel());
			}
		}
		*/
	}
	
	
	
	@Transactional
	@Override
	public Map<String,Object> accountPaymentConfirm(String rowID, String tUsercode, String tUsername, String userId, String employeeNo, String employeeName){
		AccountPayment obj = accountPaymentService.getByID(rowID);
//		List<AccountPayment> objs = accountPaymentService.getByMasterID(rowID);
//		List<AccountPayableDetail> objs2 = accountPayableDetailService.getByMasterID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getAccountPaymentNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		//如果已经提交完成，则忽略
		if("confirm".equals(obj.getState())) return mapMessage.toMap();

		//首先审核从表
		int rtn = accountPaymentDetailService.confirmByMasterID(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode("100001");
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo("主表提交失败！");
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		//然后审核主表
		rtn = accountPaymentService.confirm(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode("100001");
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo("从表提交失败！");
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		//自动审核
		if(obj.getFlowType()==0){
			//审核
			Map<String,Object> map = this.accountPaymentAgreeIt(rowID, tUsercode, tUsername, userId, employeeNo, employeeName);
			mapMessage.fromMap(map);
			//检查结果是否包括失败状态，如果包括，直接返回
			if (mapMessage.getStatusFlag().equals(MapMessage.STATUSINFO_FAILURE_FLAG)){
				return mapMessage.toMap();
			}
		}
		
		return mapMessage.toMap();
	}

	@Transactional
	@Override
	public Map<String,Object> accountPaymentActive(String rowID){
		AccountPayment obj = accountPaymentService.getByID(rowID);
		
//		List<AccountPayment> objs = accountPaymentService.getByMasterID(rowID);
//		List<AccountPayableDetail> objs2 = accountPayableDetailService.getByMasterID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getAccountPaymentNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		//首先审核从表
		int rtn = accountPaymentDetailService.activeByMasterID(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode("100001");
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo("主表撤销提交失败！");
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		
		//然后审核主表
		rtn = accountPaymentService.active(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode("100001");
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo("从表撤销提交失败！");
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		return mapMessage.toMap();
	}

	//审核出入库单（改造为主从表不关联审核）
	@Transactional
	@Override
	public Map<String,Object> accountPaymentAgreeIt(String rowID, String tUsercode, String tUsername, String userId, String employeeNo, String employeeName){
		AccountPayment accountPayment = accountPaymentService.getByID(rowID);
		
		MapMessage mapMessage = new MapMessage(accountPayment.getfID(),accountPayment.getAccountPaymentNo(),accountPayment.getBillType(),accountPayment.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		

		
//		accountPaymentService.agreeItByMasterID(rowID, tUsercode, tUsername, userId);
		List<AccountPaymentDetail> accountPaymentDetails = accountPaymentDetailService.getByMasterID(rowID);
		for(AccountPaymentDetail accountPaymentDetail : accountPaymentDetails){
			accountPaymentDetailService.agreeIt(accountPaymentDetail, tUsercode, tUsername, userId);
			this.doItPaymentDetail(accountPaymentDetail);
		}
		
		//然后审核主表
		accountPaymentService.agreeIt(accountPayment, tUsercode, tUsername, userId);
		this.doItPayment(accountPayment);
		//////////////////////////////////////////////////////////////////////////////////////////////
		//产生凭证
		/*
		JSONObject json = (JSONObject) JSON.toJSON(obj);
		json.put("cUsercode", tUsercode);
		json.put("cUsername", tUsername);
		json.put("userId", userId);
		
		JSONArray slaves = SystemService.getJSONArrayByList(accountPaymentService.getByMasterID(rowID));
		json.put("slaves", slaves);
		String voucher = accountVoucherService.insertFromPayment(json);
		System.out.println("voucher-->"+voucher);
		*/
		//更新源单的凭证号
		
		////////////////////////////////////////////////////////////////////////////////////////////
		
		return mapMessage.toMap();

	}

	@Transactional
	@Override
	public Map<String,Object> accountPaymentUnAgree(String rowID){
		AccountPayment accountPayment = accountPaymentService.getByID(rowID);
		
//		List<AccountPayment> objs = accountPaymentService.getByMasterID(rowID);
//		List<AccountPayableDetail> objs2 = accountPayableDetailService.getByMasterID(rowID);
		
		MapMessage mapMessage = new MapMessage(accountPayment.getfID(),accountPayment.getAccountPaymentNo(),accountPayment.getBillType(),accountPayment.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		if(accountPayment.getBillType().equals("YSKD") || accountPayment.getBillType().equals("YFKD")){
			//判断是否可以撤销审核
			if(accountPayment.getOrderAmount().compareTo(accountPayment.getPendingAmount())!=0){
				//已核销，无法撤销审核
				mapMessage.setStatusCode("100001");
				mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
				mapMessage.setStatusInfo("单据已核销，无法撤销审核！");
				mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			}
			//检查结果是否包括失败状态，如果包括，直接返回
			if (mapMessage.getStatusFlag().equals(MapMessage.STATUSINFO_FAILURE_FLAG)){
				return mapMessage.toMap();
			}
		}

		//首先审核从表
//		accountClosureService.unAgreeByMasterID(rowID);
		List<AccountPaymentDetail> accountPaymentDetails = accountPaymentDetailService.getByMasterID(rowID);
		for(AccountPaymentDetail accountPaymentDetail : accountPaymentDetails){
			accountPaymentDetailService.unAgree(accountPaymentDetail);
			this.unDoPaymentDetail(accountPaymentDetail);
		}
		
		//然后审核主表
		accountPaymentService.unAgree(rowID);
		this.unDoPayment(accountPayment);

	
		return mapMessage.toMap();

	}

	@Transactional
	@Override
	public int accountPaymentClose(String rowID){
		System.out.println("调用accountPaymentClose");
		this.beforeDeletePayment(rowID);
		
		//首先审核从表
		int rtn = accountPaymentDetailService.closeByMasterID(rowID);
		if (rtn != 0){
			return -1;
		}
		
		//然后审核主表
		rtn = accountPaymentService.close(rowID);
		if (rtn != 0){
			return -1;
		}
		
		return 0;
	}

	@Transactional
	@Override
	public int accountPaymentOpen(String rowID){
		AccountPayment obj = accountPaymentService.getByID(rowID);

		this.afterInsertPayment(obj);

		//首先审核从表
		int rtn = accountPaymentDetailService.openByMasterID(rowID);
		if (rtn != 0){
			return -1;
		}
		
		//然后审核主表
		rtn = accountPaymentService.open(rowID);
		if (rtn != 0){
			return -1;
		}
		
		return 0;
	}

	
	@Override
	public void accountPaymentPrintPDF(String fID, Document doc) throws Exception {
		
//	@Test
//	public void saleOrderPrintPDF() throws Exception {
//		log.info("fID-->"+id);
		
//	    Document doc = new Document();// 创建一个PDF文档，我们的PDF内容都写在上面
	    
//	    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File("c://pdftest//saleOrder.pdf"))); // 将pdf文档写入文件

//		String fID = "bf61ec2bc8163a3ad3d8572ad2fee7c6";
		AccountPayment accountPayment = accountPaymentService.getByID(fID);
	   
//	    response.setContentType("application/pdf");
//	    PdfWriter.getInstance(doc, response.getOutputStream());
//	    
//	    doc.open();
	    
	    Font fontEN = new Font(BaseFont.createFont(),9);
	    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);  	    
//	    Font font = new Font(baseFont, 10, Font.ITALIC);
	    Font fontCN = new Font(baseFont, 9);
	    Paragraph pEnterpriseName = new Paragraph(accountPayment.getEnterpriseName(),fontCN);
	    // 居中显示
	    pEnterpriseName.setAlignment(Element.ALIGN_CENTER);
	    pEnterpriseName.setSpacingAfter(-10);
	    Paragraph pBillTypeName = new Paragraph(accountPayment.getBillTypeName(),new Font(baseFont,20));
	    // 居中显示
	    pBillTypeName.setAlignment(Element.ALIGN_CENTER);
	    
	    //标题分割线
	    LineSeparator line = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, -5f);

	    	    
	    
	    
	    
	    doc.add(pEnterpriseName);
	    doc.add(pBillTypeName);
	    doc.add(line);
	    
	    
	    //默认付款单
	    //主表
	    String orderAmountMLabel = "实付金额:";
	    //子表
	    String orderAmountLabel= "应付票据金额";
	    String pendingAmountLabel= "应付票据余额";
	    String invoiceCategoryLabel = "应付票据类型";
	    String captionNameLabel = "应付科目";
	    
	    String originNoLabel = null;
	    String originNoValue = null;
	    
	    if(accountPayment.getBillType().equals("YFKD") || accountPayment.getBillType().equals("YSKD")){
	    	originNoLabel = "订单单号";
	    	originNoValue = accountPayment.getOriginNo();
	    }
	    
	    //付款单
	    if(accountPayment.getBillType().equals("FKDJ") || accountPayment.getBillType().equals("YFKD")){
		    //主表
		    orderAmountMLabel = "实付金额:";
		    //子表
		    orderAmountLabel= "应付票据金额";
		    pendingAmountLabel= "应付票据余额";
		    invoiceCategoryLabel = "应付票据类型";
		    captionNameLabel = "应付科目";
	    	
	    }
	    
	    //付款退款单
	    if(accountPayment.getBillType().equals("FTDJ")){
		    //主表
		    orderAmountMLabel = "实退金额:";
		    //子表
		    orderAmountLabel= "应付票据金额";
		    pendingAmountLabel= "应付票据余额";
		    invoiceCategoryLabel = "应付票据类型";
		    captionNameLabel = "应付科目";
	    	
	    }
	    
	    //收款单
	    if(accountPayment.getBillType().equals("SKDJ") || accountPayment.getBillType().equals("YSKD")){
		    //主表
		    orderAmountMLabel = "实收金额:";
		    //子表
		    orderAmountLabel= "应收票据金额";
		    pendingAmountLabel= "应收票据余额";
		    invoiceCategoryLabel = "应收票据类型";
		    captionNameLabel = "应收科目";
	    	
	    }
	    
	    //收款单
	    if(accountPayment.getBillType().equals("STDJ")){
		    //主表
		    orderAmountMLabel = "实退金额:";
		    //子表
		    orderAmountLabel= "应收票据金额";
		    pendingAmountLabel= "应收票据余额";
		    invoiceCategoryLabel = "应收票据类型";
		    captionNameLabel = "应收科目";
	    	
	    }
	    
	    
        PdfPTable masterHead = new PdfPTable(8);
        
//        masterHead.setTotalWidth(new float[]{60, 200, 60, 200});
        masterHead.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
        masterHead.setLockedWidth(true);
        masterHead.setSpacingBefore(10);
        
        PdfPCell ordrDateCell = new PdfPCell(new Phrase("单据日期:", fontCN));
        ordrDateCell.setUseBorderPadding(true);
        //
        // Setting cell's border width and color
        //
        ordrDateCell.setBorderWidth(0f);
//        ordrDateCell.setBorderColor(BaseColor.BLUE);
        masterHead.addCell(ordrDateCell);

        PdfPCell ordrDateValue = new PdfPCell(new Phrase(accountPayment.getOrderDate().toString(), fontEN));
        ordrDateValue.setUseBorderPadding(true);
        ordrDateValue.setBorderWidth(0f);
        //
        // Setting cell's background color
        //
//        cell2.setBackgroundColor(BaseColor.GRAY);
        //
        // Setting cell's individual border color
        //
//        cell2.setBorderWidthTop(1f);
//        cell2.setBorderColorTop(BaseColor.RED);
//        cell2.setBorderColorRight(BaseColor.GREEN);
//        cell2.setBorderColorBottom(BaseColor.BLUE);
//        cell2.setBorderColorLeft(BaseColor.BLACK);
        masterHead.addCell(ordrDateValue);

        PdfPCell auditCell = new PdfPCell(new Phrase("单据状态:", fontCN));
        auditCell.setUseBorderPadding(true);
        auditCell.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell3.setBorderWidthTop(2f);
//        cell3.setBorderWidthRight(1f);
//        cell3.setBorderWidthBottom(2f);
//        cell3.setBorderWidthLeft(1f);
        masterHead.addCell(auditCell);

        String auditStatus = "待审核";
        String audit = accountPayment.getAudit();
        String state = accountPayment.getState();
        if(audit.equals("confirm")){
        	auditStatus = "已审核";
        }else if(audit.equals("active") && state.equals("confirm")){
        	auditStatus = "审核中";
        }else{
        	auditStatus = "待审核";
        }
        
       PdfPCell auditValue = new PdfPCell(new Phrase(auditStatus, fontCN));
       auditValue.setUseBorderPadding(true);
       auditValue.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell4.setBorderWidthTop(2f);
//        cell4.setBorderWidthRight(1f);
//        cell4.setBorderWidthBottom(2f);
//        cell4.setBorderWidthLeft(1f);
        masterHead.addCell(auditValue);
        
        PdfPCell customerNoCell = new PdfPCell(new Phrase("对象编码:", fontCN));
        customerNoCell.setBorder(0);
        masterHead.addCell(customerNoCell);
        PdfPCell customerNoValue = new PdfPCell(new Phrase(accountPayment.getCustomerNo(), fontEN));
        customerNoValue.setBorder(0);
        masterHead.addCell(customerNoValue);
        
        PdfPCell shortNameCell = new PdfPCell(new Phrase("对象简称:", fontCN));
        shortNameCell.setBorder(0);
        masterHead.addCell(shortNameCell);
        PdfPCell shortNameValue = new PdfPCell(new Phrase(accountPayment.getShortName(), fontCN));
        shortNameValue.setBorder(0);
        masterHead.addCell(shortNameValue);

        //第一行结束
        masterHead.completeRow();
        
        PdfPCell orderNoCell = new PdfPCell(new PdfPCell(new Phrase("单号:", fontCN)));
        orderNoCell.setBorder(0);
        masterHead.addCell(orderNoCell);
        PdfPCell orderNoValue = new PdfPCell(new PdfPCell(new Phrase(accountPayment.getAccountPaymentNo(), fontEN)));
        orderNoValue.setBorder(0);
        masterHead.addCell(orderNoValue);
        
        PdfPCell discountRateMCell = new PdfPCell(new PdfPCell(new Phrase("", fontCN)));
        discountRateMCell.setBorder(0);
        masterHead.addCell(discountRateMCell);
        PdfPCell discountRateMValue = new PdfPCell(new PdfPCell(new Phrase("", fontEN)));
        discountRateMValue.setBorder(0);
        masterHead.addCell(discountRateMValue);
        
        PdfPCell customerNameCell = new PdfPCell(new Phrase("交易对象:", fontCN));
        customerNameCell.setBorder(0);
        masterHead.addCell(customerNameCell);
        PdfPCell customerNameValue = new PdfPCell(new Phrase(accountPayment.getCustomerName(), fontCN));
        customerNameValue.setBorder(0);
        customerNameValue.setColspan(3);
        masterHead.addCell(customerNameValue);
        //第二行结束
        masterHead.completeRow();
        
        PdfPCell employeeNameCell = new PdfPCell(new Phrase("经办人:", fontCN));
        employeeNameCell.setBorder(0);
        masterHead.addCell(employeeNameCell);
        PdfPCell employeeNameValue = new PdfPCell(new Phrase(accountPayment.getEmployeeName(), fontCN));
        employeeNameValue.setBorder(0);
        employeeNameValue.setColspan(3);
        masterHead.addCell(employeeNameValue);
        
        PdfPCell accountNoCell = new PdfPCell(new PdfPCell(new Phrase("结算方式:", fontCN)));
        accountNoCell.setBorder(0);
        masterHead.addCell(accountNoCell);
        PdfPCell accountNoValue = new PdfPCell(new PdfPCell(new Phrase(accountPayment.getSettleCategoryLabel(), fontCN)));
        accountNoValue.setBorder(0);
//        accountNoValue.setColspan(3);
        masterHead.addCell(accountNoValue);
        
        PdfPCell invoiceCodeCell = new PdfPCell(new Phrase("结算号:", fontCN));
        invoiceCodeCell.setBorder(0);
        masterHead.addCell(invoiceCodeCell);
        PdfPCell invoiceCodeValue = new PdfPCell(new Phrase(accountPayment.getSettleCode(), fontCN));
        invoiceCodeValue.setBorder(0);
        masterHead.addCell(invoiceCodeValue);

        //第五行结束
        masterHead.completeRow();
        
        PdfPCell orderAmountMCell = new PdfPCell(new Phrase(orderAmountMLabel, fontCN));
        orderAmountMCell.setBorder(0);
        masterHead.addCell(orderAmountMCell);
        PdfPCell orderAmountMValue = new PdfPCell(new Phrase(accountPayment.getOrderAmount().toString(), fontEN));
        orderAmountMValue.setBorder(0);
        masterHead.addCell(orderAmountMValue);
        
        PdfPCell invoiceDateCell = new PdfPCell(new Phrase("现金折扣:", fontCN));
        invoiceDateCell.setBorder(0);
        masterHead.addCell(invoiceDateCell);
        PdfPCell invoiceDateValue = new PdfPCell(new Phrase(accountPayment.getDiscountCash().toString(), fontEN));
        invoiceDateValue.setBorder(0);
        masterHead.addCell(invoiceDateValue);
        
        PdfPCell taxNoCell = new PdfPCell(new Phrase("单据金额:", fontCN));
        taxNoCell.setBorder(0);
        masterHead.addCell(taxNoCell);
        PdfPCell taxNoValue = new PdfPCell(new Phrase(accountPayment.getOrderAmountTotal().toString(), fontEN));
        taxNoValue.setBorder(0);
        masterHead.addCell(taxNoValue);
        
        PdfPCell predictDateCell = new PdfPCell(new Phrase(originNoLabel, fontCN));
        predictDateCell.setBorder(0);
        masterHead.addCell(predictDateCell);
        PdfPCell predictDateValue = new PdfPCell(new Phrase(originNoValue, fontCN));
        predictDateValue.setBorder(0);
        masterHead.addCell(predictDateValue);
        //第六行结束
        masterHead.completeRow();
        
        PdfPCell commentsCell = new PdfPCell(new Phrase("备注:", fontCN));
        commentsCell.setBorder(0);
        masterHead.addCell(commentsCell);
        PdfPCell commentsValue = new PdfPCell(new Phrase(accountPayment.getComments(), fontCN));
        commentsValue.setBorder(0);
        commentsValue.setColspan(7);
        masterHead.addCell(commentsValue);
        
        //第n行结束
        masterHead.completeRow();

        doc.add(masterHead);
//	    doc.add(line);
	    

        /*
        Image image = Image.getInstance("c://pdftest//smp.png");

        image.setAlignment(Image.ALIGN_RIGHT);
        // 设置边框
        image.setBorder(Image.BOX);
        image.setBorderWidth(2);
        image.setBorderColor(BaseColor.RED);
        // 设置图片大小
        
//        ScaleToFit有两个参数，指的是长和宽的最大值，但是图片的长宽比还是不会变的
//        ScaleAbsoluteHeight设置图片的高度，不管长宽比 ScaleAbsoluteWidth设置图片的宽度，不管长宽比
//        ScalePercent等比例缩放
        
//         image.scaleToFit(100, 100);
//         image.scaleAbsoluteHeight(100f);
//         image.scaleAbsoluteWidth(100f);

        image.scalePercent(50f);
        // 图片旋转30度
        image.setRotationDegrees(30);

        doc.add(image);
        */
        
        
        
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
	    
        PdfPTable details = new PdfPTable(8);
        details.setTotalWidth(new float[]{15, 70, 70, 80, 65, 75, 65, 80});//520
        details.setLockedWidth(true);
        details.setSpacingBefore(10);

        PdfPCell sharpCell = new PdfPCell(new Phrase("序号", fontCN));
//        sharpCell.setBorder(0);
        sharpCell.setRowspan(3);
        sharpCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        sharpCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        details.addCell(sharpCell);

        PdfPCell itemNoCell = new PdfPCell(new Phrase("来源单号", fontCN));
//        itemNoCell.setBorder(0);
//        itemNoCell.setBorderWidthTop(0);
        itemNoCell.setBorderWidthLeft(0);
        itemNoCell.setBorderWidthBottom(0);
        itemNoCell.setBorderWidthRight(0);
        itemNoCell.setColspan(2);
        details.addCell(itemNoCell);

        PdfPCell projectNoCell = new PdfPCell(new Phrase("来源", fontCN));
//        projectNoCell.setBorder(0);
        projectNoCell.setBorderWidthLeft(0);
        projectNoCell.setBorderWidthBottom(0);
        projectNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(projectNoCell);

        PdfPCell requirementDateCell = new PdfPCell(new Phrase(orderAmountLabel, fontCN));
//        requirementDateCell.setBorder(0);
        requirementDateCell.setBorderWidthLeft(0);
        requirementDateCell.setBorderWidthBottom(0);
        requirementDateCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(requirementDateCell);

        PdfPCell itemAmountsCell = new PdfPCell(new Phrase("折扣金额", fontCN));
//        itemAmountsCell.setBorder(0);
        itemAmountsCell.setBorderWidthLeft(0);
        itemAmountsCell.setBorderWidthBottom(0);
        itemAmountsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(itemAmountsCell);

        PdfPCell taxRatesCell = new PdfPCell(new Phrase("本次核销金额", fontCN));
//        taxRatesCell.setBorder(0);
        taxRatesCell.setBorderWidthLeft(0);
        taxRatesCell.setBorderWidthBottom(0);
        taxRatesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(taxRatesCell);

        PdfPCell commentssCell = new PdfPCell(new Phrase("备注", fontCN));
//        commentssCell.setBorder(0);
        commentssCell.setBorderWidthLeft(0);
        commentssCell.setRowspan(3);
        details.addCell(commentssCell);
        
        details.completeRow();
        //第一行结束
        //第二行结束

        PdfPCell itemPropertyCell = new PdfPCell(new Phrase("发票号", fontCN));
//        itemPropertyCell.setBorder(0);
        itemPropertyCell.setBorderWidthTop(0);
        itemPropertyCell.setBorderWidthLeft(0);
        itemPropertyCell.setBorderWidthBottom(0);
        itemPropertyCell.setBorderWidthRight(0);
        itemPropertyCell.setColspan(2);
        details.addCell(itemPropertyCell);

        PdfPCell unitNameCell = new PdfPCell(new Phrase(invoiceCategoryLabel, fontCN));
//        unitNameCell.setBorder(0);
        unitNameCell.setBorderWidthTop(0);
        unitNameCell.setBorderWidthLeft(0);
        unitNameCell.setBorderWidthBottom(0);
        unitNameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(unitNameCell);

        PdfPCell discountRateCell = new PdfPCell(new Phrase(pendingAmountLabel, fontCN));
//        discountRateCell.setBorder(0);
        discountRateCell.setBorderWidthTop(0);
        discountRateCell.setBorderWidthLeft(0);
        discountRateCell.setBorderWidthBottom(0);
        discountRateCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(discountRateCell);

        PdfPCell itemPriceCell = new PdfPCell(new Phrase("", fontCN));
//        itemPriceCell.setBorder(0);
        itemPriceCell.setBorderWidthTop(0);
        itemPriceCell.setBorderWidthLeft(0);
        itemPriceCell.setBorderWidthBottom(0);
        itemPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(itemPriceCell);

        PdfPCell orderAmountTaxsCell = new PdfPCell(new Phrase("", fontCN));
//        orderAmountTaxsCell.setBorder(0);
        orderAmountTaxsCell.setBorderWidthTop(0);
        orderAmountTaxsCell.setBorderWidthLeft(0);
        orderAmountTaxsCell.setBorderWidthBottom(0);
        orderAmountTaxsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTaxsCell);

        details.completeRow();
        //第三行结束

        PdfPCell floorNoCell = new PdfPCell(new Phrase("科目名称", fontCN));
//        floorNoCell.setBorder(0);
        floorNoCell.setBorderWidthTop(0);
        floorNoCell.setBorderWidthLeft(0);
        floorNoCell.setBorderWidthRight(0);
        floorNoCell.setColspan(2);
        details.addCell(floorNoCell);

        PdfPCell storageNoCell = new PdfPCell(new Phrase(captionNameLabel, fontCN));
//        storageNoCell.setBorder(0);
        storageNoCell.setBorderWidthTop(0);
        storageNoCell.setBorderWidthLeft(0);
        storageNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(storageNoCell);

        PdfPCell emptyCell = new PdfPCell(new Phrase("票据日期", fontCN));
//        emptyCell.setBorder(0);
        emptyCell.setBorderWidthTop(0);
        emptyCell.setBorderWidthLeft(0);
        emptyCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(emptyCell);

        PdfPCell orderAmountCell = new PdfPCell(new Phrase("", fontCN));
//        orderAmountCell.setBorder(0);
        orderAmountCell.setBorderWidthTop(0);
        orderAmountCell.setBorderWidthLeft(0);
        orderAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountCell);

        PdfPCell orderAmountTotalsCell = new PdfPCell(new Phrase("", fontCN));
//        orderAmountTotalsCell.setBorder(0);
        orderAmountTotalsCell.setBorderWidthTop(0);
        orderAmountTotalsCell.setBorderWidthLeft(0);
        orderAmountTotalsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTotalsCell);

        details.completeRow();
        //第四行结束
        
        
//        doc.add(details);
        
        ////////////////////////////////////////////////////////////////////////////////////////////
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
        List<AccountPaymentDetail> accountPaymentDetails = accountPaymentDetailService.getByMasterID(fID);
        if(accountPaymentDetails.size()>0){
    	    
//            PdfPTable detailsValue = new PdfPTable(8);
//            
//            detailsValue.setTotalWidth(new float[]{20, 70, 70, 80, 80, 80, 60, 60});//520
//            detailsValue.setLockedWidth(true);
//            detailsValue.setSpacingBefore(10);
            
            for(int i=0;i<accountPaymentDetails.size();i++){
            	AccountPaymentDetail accountPaymentDetail = accountPaymentDetails.get(i);

            	//序号
            	String rowNo = String.valueOf(i+1);
                PdfPCell sharpValue = new PdfPCell(new Phrase(rowNo, fontEN));
//                sharpValue.setBorder(0);
                sharpValue.setBorderWidthTop(0);
                sharpValue.setRowspan(3);
                sharpValue.setHorizontalAlignment(Element.ALIGN_CENTER);
                sharpValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
                details.addCell(sharpValue);

                PdfPCell itemNoValue = new PdfPCell(new Phrase(accountPaymentDetail.getOriginNo(), fontEN));
//                itemNoValue.setBorder(0);
                itemNoValue.setBorderWidthTop(0);
                itemNoValue.setBorderWidthLeft(0);
                itemNoValue.setBorderWidthBottom(0);
                itemNoValue.setBorderWidthRight(0);
                itemNoValue.setColspan(2);
                details.addCell(itemNoValue);

                PdfPCell projectNoValue = new PdfPCell(new Phrase(accountPaymentDetail.getOriginName(), fontCN));
//                projectNoValue.setBorder(0);
                projectNoValue.setBorderWidthTop(0);
                projectNoValue.setBorderWidthLeft(0);
                projectNoValue.setBorderWidthBottom(0);
                projectNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(projectNoValue);

                PdfPCell requirementDateValue = new PdfPCell(new Phrase(accountPaymentDetail.getOrderAmount().toString(), fontEN));
//                requirementDateValue.setBorder(0);
                requirementDateValue.setBorderWidthTop(0);
                requirementDateValue.setBorderWidthLeft(0);
                requirementDateValue.setBorderWidthBottom(0);
                requirementDateValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(requirementDateValue);

                PdfPCell itemAmountValue = new PdfPCell(new Phrase(accountPaymentDetail.getDiscountCash().toString(), fontEN));
//                itemAmountValue.setBorder(0);
                itemAmountValue.setBorderWidthTop(0);
                itemAmountValue.setBorderWidthLeft(0);
                itemAmountValue.setBorderWidthBottom(0);
                itemAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(itemAmountValue);

                PdfPCell taxRatesValue = new PdfPCell(new Phrase(accountPaymentDetail.getOrderAmountCleared().toString(), fontEN));
//                taxRatesValue.setBorder(0);
                taxRatesValue.setBorderWidthTop(0);
                taxRatesValue.setBorderWidthLeft(0);
                taxRatesValue.setBorderWidthBottom(0);
                taxRatesValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(taxRatesValue);

                PdfPCell commentssValue = new PdfPCell(new Phrase(accountPaymentDetail.getComments(), fontCN));
//                commentssValue.setBorder(0);
                commentssValue.setBorderWidthTop(0);
                commentssValue.setBorderWidthLeft(0);
                commentssValue.setRowspan(3);
                details.addCell(commentssValue);
                
                details.completeRow();
                //第一行结束

              PdfPCell itemPropertyValue = new PdfPCell(new Phrase(accountPaymentDetail.getSettleCode(), fontCN));
//              itemPropertyValue.setBorder(0);
              itemPropertyValue.setBorderWidthTop(0);
              itemPropertyValue.setBorderWidthLeft(0);
              itemPropertyValue.setBorderWidthBottom(0);
              itemPropertyValue.setBorderWidthRight(0);
              itemPropertyValue.setColspan(2);
              details.addCell(itemPropertyValue);

              PdfPCell unitNameValue = new PdfPCell(new Phrase("", fontCN));
//              unitNameValue.setBorder(0);
              unitNameValue.setBorderWidthTop(0);
              unitNameValue.setBorderWidthLeft(0);
              unitNameValue.setBorderWidthBottom(0);
              unitNameValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(unitNameValue);

              PdfPCell discountRateValue = new PdfPCell(new Phrase(accountPaymentDetail.getOrderAmount().toString(), fontEN));
//              discountRateValue.setBorder(0);
              discountRateValue.setBorderWidthTop(0);
              discountRateValue.setBorderWidthLeft(0);
              discountRateValue.setBorderWidthBottom(0);
              discountRateValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(discountRateValue);

              PdfPCell itemPriceValue = new PdfPCell(new Phrase("", fontEN));
//              itemPriceValue.setBorder(0);
              itemPriceValue.setBorderWidthTop(0);
              itemPriceValue.setBorderWidthLeft(0);
              itemPriceValue.setBorderWidthBottom(0);
              itemPriceValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(itemPriceValue);

              PdfPCell orderAmountTaxValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountTaxValue.setBorder(0);
              orderAmountTaxValue.setBorderWidthTop(0);
              orderAmountTaxValue.setBorderWidthLeft(0);
              orderAmountTaxValue.setBorderWidthBottom(0);
              orderAmountTaxValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTaxValue);

              details.completeRow();
              //第二行结束
              

              PdfPCell floorNoValue = new PdfPCell(new Phrase(accountPaymentDetail.getCaptionFullName(), fontCN));
//              floorNoValue.setBorder(0);
              floorNoValue.setBorderWidthTop(0);
              floorNoValue.setBorderWidthLeft(0);
              floorNoValue.setBorderWidthRight(0);
              floorNoValue.setColspan(2);
              details.addCell(floorNoValue);

              PdfPCell storageNoValue = new PdfPCell(new Phrase(accountPaymentDetail.getCaptionNo(), fontCN));
//              storageNoValue.setBorder(0);
              storageNoValue.setBorderWidthTop(0);
              storageNoValue.setBorderWidthLeft(0);
              storageNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(storageNoValue);

              PdfPCell emptyValue = new PdfPCell(new Phrase(accountPaymentDetail.getSettleDate()==null?null:accountPaymentDetail.getSettleDate().toString(), fontEN));
//              emptyValue.setBorder(0);
              emptyValue.setBorderWidthTop(0);
              emptyValue.setBorderWidthLeft(0);
              emptyValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(emptyValue);

              PdfPCell orderAmountValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountValue.setBorder(0);
              orderAmountValue.setBorderWidthTop(0);
              orderAmountValue.setBorderWidthLeft(0);
              orderAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountValue);

              PdfPCell orderAmountTotalValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountTotalValue.setBorder(0);
              orderAmountTotalValue.setBorderWidthTop(0);
              orderAmountTotalValue.setBorderWidthLeft(0);
              orderAmountTotalValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTotalValue);

              details.completeRow();
              //第三行结束
              
            }
            
            doc.add(details);
            //子表结束
            
            
            
//    	    doc.add(line);

    	    
            PdfPTable masterFoot = new PdfPTable(8);
            
            masterFoot.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
            masterFoot.setLockedWidth(true);
//            masterFoot.setSpacingBefore(10);

            PdfPCell detailsCountCell = new PdfPCell(new Phrase("核销金额:", fontCN));
//            detailsCountCell.setBorder(0);
            detailsCountCell.setBorderWidthTop(0);
//            detailsCountCell.setBorderWidthBottom(0);
            detailsCountCell.setBorderWidthRight(0);
            masterFoot.addCell(detailsCountCell);

            PdfPCell detailsCountValue = new PdfPCell(new Phrase(String.valueOf(accountPayment.getOrderAmount()), fontEN));
            detailsCountValue.setBorderWidthTop(0);
//          detailsCountValue.setBorderWidthBottom(0);
            detailsCountValue.setBorderWidthLeft(0);
            detailsCountValue.setBorderWidthRight(0);
            masterFoot.addCell(detailsCountValue);

            PdfPCell r1emptyCell = new PdfPCell(new Phrase(""));
//            r1emptyCell.setBorder(0);
            r1emptyCell.setBorderWidthTop(0);
//            r1emptyCell.setBorderWidthBottom(0);
            r1emptyCell.setBorderWidthLeft(0);
            r1emptyCell.setColspan(6);
            masterFoot.addCell(r1emptyCell);

            //第一行结束
            masterFoot.completeRow();

            doc.add(masterFoot);
           	
        }else{
    	    
    	    //页脚分割线
    	    LineSeparator line1 = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, -5f);
    	    doc.add(line1);
        	
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
       
        
        
	    
        PdfPTable masterTail = new PdfPTable(8);
        
        masterTail.setTotalWidth(new float[]{45, 65, 45, 105, 45, 65, 45, 105});
        masterTail.setLockedWidth(true);
        masterTail.setSpacingBefore(10);

        PdfPCell cUsernameCell = new PdfPCell(new Phrase("制单:", fontCN));
        cUsernameCell.setBorder(0);
        masterTail.addCell(cUsernameCell);

        PdfPCell cUsernameValue = new PdfPCell(new Phrase(accountPayment.getcUsername(), fontCN));
        cUsernameValue.setBorder(0);
        masterTail.addCell(cUsernameValue);

        PdfPCell cDatetimeCell = new PdfPCell(new Phrase("制单时间:", fontCN));
        cDatetimeCell.setBorder(0);
        masterTail.addCell(cDatetimeCell);

        PdfPCell cDatetimeValue = new PdfPCell(new Phrase(accountPayment.getcDatetime().toString(), fontEN));
        cDatetimeValue.setBorder(0);
        masterTail.addCell(cDatetimeValue);

        PdfPCell tUsernameCell = new PdfPCell(new Phrase("审核:", fontCN));
        tUsernameCell.setBorder(0);
        masterTail.addCell(tUsernameCell);

        PdfPCell tUsernameValue = new PdfPCell(new Phrase(accountPayment.gettUsername(), fontCN));
        tUsernameValue.setBorder(0);
        masterTail.addCell(tUsernameValue);

        PdfPCell tDatetimeCell = new PdfPCell(new Phrase("审核时间:", fontCN));
        tDatetimeCell.setBorder(0);
        masterTail.addCell(tDatetimeCell);

        PdfPCell tDatetimeValue = new PdfPCell(new Phrase(accountPayment.gettDatetime()==null?"":accountPayment.gettDatetime().toString(), fontEN));
        tDatetimeValue.setBorder(0);
        masterTail.addCell(tDatetimeValue);


        masterTail.completeRow();
        

        doc.add(masterTail);
	    
        Chunk printTimeChunk = new Chunk("打印时间: ",fontCN);
        String printTime = Utils.getCurrentDateTime().toString();
        Paragraph printTimeParagraph = new Paragraph(printTimeChunk);
        Chunk printTimeValueChunk = new Chunk(printTime,fontEN);
        printTimeParagraph.add(printTimeValueChunk);
        printTimeParagraph.setAlignment(Element.ALIGN_RIGHT);
	    doc.add(printTimeParagraph);
	    
        
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	 

	    
//	    doc.close();
	    
	    
	    
	    
//        int pageNumber = doc.getPageNumber();
//        System.out.println(pageNumber);
//	    Rectangle rect = doc.getPageSize();
//	    System.out.println("rect.getHeight()-->"+rect.getHeight());
//	    System.out.println("rect.getWidth()-->"+rect.getWidth());
//	    System.out.println("rect.getLeft()-->"+rect.getLeft());
//	    System.out.println("rect.getTop()-->"+rect.getTop());
//	    System.out.println("rect.getBottom()-->"+rect.getBottom());
//	    System.out.println("rect.getRight()-->"+rect.getRight());
//	    System.out.println("rect.getBorder()-->"+rect.getBorder());
//	    System.out.println("rect.getBorderWidth()-->"+rect.getBorderWidth());
//	    System.out.println("rect.getBorderWidthTop()-->"+rect.getBorderWidthTop());
//	    System.out.println("rect.getBorderWidthLeft()-->"+rect.getBorderWidthLeft());
//	    System.out.println("rect.getBorderWidthBottom()-->"+rect.getBorderWidthBottom());
//	    System.out.println("rect.getBorderWidthRight()-->"+rect.getBorderWidthRight());

	}

	/*
	@Override
	public void cashierXSFPPrintPDF(@RequestParam(value="id",required=true) String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
//		log.info("fID-->"+id);
		accountInvoiceService.dinnerOrderPrintPDF(id, response);
	}
	*/

	//预收款单
	@Transactional
	@Override
	public AccountPayment accountPaymentYSKDInsert(
			SaleOrder saleOrder,
			String cUsercode, String cUsername, String userId
			, String employeeNo, String employeeName){

		
		if(saleOrder==null) {
			return null;
		}
		
		String dealObject = null;
		String dealObjectLabel = null;
		String customerID = null;
		String customerNo = null;
		String shortName = null;
		String customerName = null;
		
		dealObject = saleOrder.getStorageTypeD();
		dealObjectLabel = saleOrder.getStorageTypeDLabel();
		customerID = saleOrder.getCustomerID();
		customerNo = saleOrder.getCustomerNo();
		shortName = saleOrder.getShortName();
		customerName = saleOrder.getCustomerName();
		
		String origin = saleOrder.getBillType();
		String originName = saleOrder.getBillTypeName();
		String originNo = saleOrder.getOrderNo();

		String remark = saleOrder.getBillTypeName();
		BigDecimal orderAmount = saleOrder.getOrderAmountTotal();
		
		
		String orderNo = saleOrder.getOrderNo();
		String tradeNo = null;
		String guestNumber = null;
		
		int flowType = 0;//提交后自动审批

		int cashSettle = 0;//现结
		
		String enterpriseNo = saleOrder.getEnterpriseNo();
		String enterpriseName = saleOrder.getEnterpriseName();

//		String capitalID = null;
//		String capitalNo = null;
//		String capitalName = null;
//		String capitalFullName = null;//资金账户名称
		
		String settleCategory = saleOrder.getSettleCategory();
		String settleCategoryLabel = saleOrder.getSettleCategoryLabel();

		return accountPaymentService.accountPaymentYSKDInsert(guestNumber, origin, originName, originNo, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, remark, orderAmount, settleCategory, settleCategoryLabel, tradeNo, orderNo, flowType, cashSettle, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
	}
	
	
	//收款单（当面结算销售发票）--现结
	@Transactional
	@Override
	public AccountPayment accountPaymentSKDJInsert(
			AccountInvoice accountInvoice,
			BigDecimal orderAmount,
			BigDecimal discountCash, //现金折扣
			String tradeNo,
			String cUsercode, String cUsername, String userId
			, String employeeNo, String employeeName){

		
//		String accountInvoiceNo = params.getString("accountInvoiceNo");
//		String enterpriseNo = params.getString("enterpriseNo");
//		accountInvoice = accountInvoiceService.getXSFPByNo(accountInvoiceNo, enterpriseNo);
		
//		AccountInvoice accountInvoice = accountInvoiceService.getByID(xsfpID);
		
		if(accountInvoice==null) {
			return null;
		}
		
		if(!"unclear".equals(accountInvoice.getHandling())) {
			return null;
		}
		
		int cashSettle = 1;//现结
		
		String enterpriseNo = accountInvoice.getEnterpriseNo();
		String enterpriseName = accountInvoice.getEnterpriseName();

		String capitalID = null;
		String capitalNo = null;
		String capitalName = null;
		String capitalFullName = null;//资金账户名称
		
		/*
		SettleInfoOrg settleInfoOrg = settleInfoOrgService.getByNo(settleCategory, enterpriseNo);
		if(settleInfoOrg==null) {
			return null;
		}

		//默认资金账户
		String capitalID = settleInfoOrg.getCapitalID();
		if(capitalID!=null) {
			AccountCaption accountCaption = accountCaptionService.getByID(capitalID);
			capitalNo = accountCaption.getCaptionNo();
			capitalName = accountCaption.getCaptionName();
			capitalFullName = accountCaption.getCaptionFullName();
		}
		*/
		
		String guestNumber = accountInvoice.getGuestNumber();
		
		String clearType = "6";
		String clearTypeLabel = "6.到款核销";
		
		String dealObject = null;
		String dealObjectLabel = null;
		String customerID = null;
		String customerNo = null;
		String shortName = null;
		String customerName = null;
		
		dealObject = accountInvoice.getDealObject();
		dealObjectLabel = accountInvoice.getDealObjectLabel();
		customerID = accountInvoice.getCustomerID();
		customerNo = accountInvoice.getCustomerNo();
		shortName = accountInvoice.getShortName();
		customerName = accountInvoice.getCustomerName();
		
		enterpriseNo = accountInvoice.getEnterpriseNo();
		enterpriseName = accountInvoice.getEnterpriseName();

		String billType = "SKDJ";//用收款单的排序号
		
		Map<String,Object> map = settingService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
		String origin = (String) map.get("origin");
		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");
		
//		int direction = accountInvoice.getDirection();
//		BigDecimal bgDirection = new BigDecimal(direction);

		flowType = 0;//提交后自动审批
		
		//主表金额
		
		////////////////////////////////////////////////////////////////////////////
		
		//打包主表AccountPayment
//		String billType = "SKDJ";
		AccountPayment accountPayment = accountPaymentService.packing(billType, billTypeName, systemCode, flowType, revOpay, direction, autoCode, origin, originName, billNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		
//		accountPayment.setClearType(clearType);
//		accountPayment.setClearTypeLabel(clearTypeLabel);
		
		accountPayment.setGuestNumber(guestNumber);

		//设置审批类型
//		if(flowType!=null){
//			accountPayment.setFlowType(Integer.parseInt(flowType));
//		}
		
		//现结
		accountPayment.setCashSettle(cashSettle);
		
		accountPayment.setDirection(direction);
		
		accountPayment.setDealObject(dealObject);
		accountPayment.setDealObjectLabel(dealObjectLabel);
		accountPayment.setCustomerID(customerID);
		accountPayment.setCustomerNo(customerNo);
		accountPayment.setShortName(shortName);
		accountPayment.setCustomerName(customerName);
		
		accountPayment.setComments("系统生成");
		
//		accountPayment.setEmployeeNo(employeeNo);
//		accountPayment.setEmployeeName(employeeName);
		
		accountPayment.setOrigin(accountPayment.getBillType());
		accountPayment.setOriginName(accountPayment.getBillTypeName());
		accountPayment.setOriginNo(accountPayment.getAccountPaymentNo());
		
//		accountPayment.setBillType(accountInvoice.getBillType());
//		accountPayment.setBillTypeName(accountInvoice.getBillTypeName());
//		accountPayment.setAccountPaymentNo(accountInvoice.getAccountInvoiceNo());
		
		String settleCategory = accountInvoice.getSettleCategory();
		String settleCategoryLabel = accountInvoice.getSettleCategoryLabel();

		//设置结算方式和资金账户
		accountPayment.setSettleCategory(settleCategory);
		accountPayment.setSettleCategoryLabel(settleCategoryLabel);
		accountPayment.setSettleDate(Utils.getCurrentDate());
		accountPayment.setSettleCode(tradeNo);
		
		accountPayment.setCapitalID(capitalID);
		accountPayment.setCapitalNo(capitalNo);
		accountPayment.setCapitalName(capitalName);
		accountPayment.setCapitalFullName(capitalFullName);
		
		////////////////////////////////////////////////////////////////////////////////////////////
		accountPayment.setOrderAmount(orderAmount);//实收金额
		accountPayment.setDiscountCash(discountCash);//现金折扣，抹零
		accountPayment.setOrderAmountTotal(accountPayment.getOrderAmount().add(accountPayment.getDiscountCash()));//单据金额
		accountPayment.setPendingAmount(BigDecimal.ZERO);//票据余额
		
		accountPayment.setOrderAmountCleared(orderAmount);
		
//		accountPayment.setReceiveCashAmount(receiveCashAmount);//收到现金
		
		//账
//		accountPayment.setAccountClearActual(orderAmount);
//		accountPayment.setAccountClearPayable(BigDecimal.ZERO);
//		accountPayment.setAccountDiscountCash(BigDecimal.ZERO);
		
		accountPayment.setHandling("cleared");
		accountPayment.setHandlingLabel("已核销");
		
		//写入数据库主表
		accountPaymentService.insert(accountPayment);

		////////////////////////////////////////////////////////////////////////////////////////////

		//插入子表（由销售发票生成，而不是由收款单生成）AccountPaymentDetail
		String writeOffNo = accountPayment.getAccountPaymentNo();
		
		String fMasterID = accountPayment.getfID();
		String invoiceCategory = accountInvoice.getInvoiceCategory();
		String invoiceCategoryLabel = accountInvoice.getInvoiceCategoryLabel();
		
		origin = accountInvoice.getBillType();
		originName = accountInvoice.getBillTypeName();
		String originNo = accountInvoice.getAccountInvoiceNo();
		Date invoiceDate = accountInvoice.getInvoiceDate();
		String invoiceCode = accountInvoice.getInvoiceCode();
		
		orderAmount = accountInvoice.getOrderAmountTotal();
		BigDecimal pendingAmount = accountInvoice.getPendingAmount();
		BigDecimal orderAmountCleared = accountInvoice.getPendingAmount();
		
		String captionID = null;
		String captionNo = null;
		String captionName = null;
		String captionFullName = null;
		
		String orderNo = accountInvoice.getOrderNo();
		String projectNo = accountInvoice.getProjectNo();

		accountPaymentDetailService.accountPaymentDetailInsert(writeOffNo, fMasterID, invoiceCategory, invoiceCategoryLabel, cashSettle, clearType, clearTypeLabel, revOpay, direction, origin, originName, originNo, invoiceDate, invoiceCode, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, orderAmount, pendingAmount, orderAmountCleared, discountCash, captionID, captionNo, captionName, captionFullName, orderNo, projectNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		
		
		//回写销售发票
		accountInvoice.setNext(accountPayment.getBillType());
		accountInvoice.setNextName(accountPayment.getBillTypeName());
		accountInvoice.setNextNo(accountPayment.getAccountPaymentNo());
		
		//结算方式
		accountInvoice.setSettleCategory(settleCategory);
		accountInvoice.setSettleCategoryLabel(settleCategoryLabel);
		
		accountInvoiceService.update(accountInvoice);
		
		//处理代金券，不在这里处理（当作现金折扣一并处理）
		/*
		if(Utils.isNotEmptyString(voucherID)) {
			//存在代金券
			AccountPayment sdjq = accountPaymentService.getByID(voucherID);
			if(sdjq!=null) {
				origin = sdjq.getBillType();
				originName = sdjq.getBillTypeName();
				originNo = sdjq.getAccountPaymentNo();
				invoiceCode = sdjq.getSettleCode();
				orderAmount = sdjq.getPendingAmount().negate();
				pendingAmount = orderAmount;
				orderAmountCleared = orderAmount;
				discountCash = BigDecimal.ZERO;
				accountPaymentDetailService.accountPaymentDetailInsert(writeOffNo, fMasterID, invoiceCategory, invoiceCategoryLabel, cashSettle, clearType, clearTypeLabel, revOpay, direction, origin, originName, originNo, invoiceDate, invoiceCode, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, orderAmount, pendingAmount, orderAmountCleared, discountCash, captionID, captionNo, captionName, captionFullName, orderNo, projectNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
			}
		}
		*/

		
		return accountPayment;
	}


	
	//检查核销批号是否存在
	@Override
	public JSONObject checkWriteOffNo(JSONObject data){
		String writeOffNo = data.getString("writeOffNo");
		String enterpriseNo = data.getString("enterpriseNo");
		
		JSONObject json = new JSONObject();
		json.put("count", accountPaymentDetailService.getByWriteOffNo(writeOffNo, enterpriseNo).size());
		
		return json;
	}
	
	//根据带入的数组核销应收应付与预收预付（同时支持收款和付款）--私有函数，同时被前端函数和后端函数调用
	@Transactional
	@Override
	public int hxArrayData(
			String writeOffNo,
			String dealObject,
			String dealObjectLabel,
			String customerID,
			String customerNo,
			String shortName,
			String customerName,
			
			String revOpay,
			
			String clearType,
			String clearTypeLabel,
		
			String billType,
			String billTypeName,
			
			BigDecimal discountCashTotal,
			JSONArray rows1,
			JSONArray rows2,
			
			String orderNo,
			String projectNo,
			
			String cUsercode, String cUsername, String userId, String employeeNo, String employeeName, String enterpriseNo, String enterpriseName
			) {
		
		//String APPID = "d5c0ac391478fbbf5d85f8e28b49236f";
		
		
		//总流水号
//		int index = 0;
		
		int cashSettle = 9;//到款核销
		int direction = 1;
		
		//到款
		//预收款单
		for(int i=0;i<rows1.size();i++){
//			index++;
			JSONObject obj = rows1.getJSONObject(i);
			String fID = obj.getString("id");
			BigDecimal clearAmount = obj.getBigDecimal("amount");
//			log.info("amount-->"+amount.toString());
			//获取会计科目（结算账户）的全路径信息
//			AccountCaption accountCaption = accountCaptionService.getByID(captionID);
//			String captionFullNo = null;// accountCaption.getCaptionFullNo();
//			String captionFullName = null;// accountCaption.getCaptionFullName();
			
			//预收款单
			AccountPayment y = accountPaymentService.getByID(fID);
			
			String fMasterID = null;
			String invoiceCategory = y.getSettleCategory();
			String invoiceCategoryLabel = y.getSettleCategoryLabel();
			
			String origin = y.getBillType();
			String originName = y.getBillTypeName();
			String originNo = y.getAccountPaymentNo();
			
			BigDecimal orderAmount = y.getOrderAmount().negate();
			BigDecimal pendingAmount = y.getPendingAmount().negate();
			BigDecimal orderAmountCleared = clearAmount.negate();
			BigDecimal discountCash = BigDecimal.ZERO;
			
			Date invoiceDate = y.getOrderDate();
			String invoiceCode = null;
			
			String captionID = null;
			String captionNo = null;
			String captionName = null;
			String captionFullName = null;
			
			AccountPaymentDetail accountPaymentDetail = accountPaymentDetailService.accountPaymentDetailInsert(writeOffNo, fMasterID, invoiceCategory, invoiceCategoryLabel, cashSettle, clearType, clearTypeLabel, revOpay, direction, origin, originName, originNo, invoiceDate, invoiceCode, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, orderAmount, pendingAmount, orderAmountCleared, discountCash, captionID, captionNo, captionName, captionFullName, orderNo, projectNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
			
			accountPaymentDetailService.agreeIt(accountPaymentDetail,cUsercode,cUsername,userId);
			this.doItPaymentDetail(accountPaymentDetail);
		}
		
		//应收款
		//销售发票
		for(int i=0;i<rows2.size();i++){
//			index++;
			JSONObject obj = rows2.getJSONObject(i);
			String fID = obj.getString("id");
			BigDecimal clearAmount = obj.getBigDecimal("amount");
			BigDecimal discountCash = obj.getBigDecimal("discountCash");
//			log.info("amount-->"+amount.toString());
			//获取会计科目（结算账户）的全路径信息
//			AccountCaption accountCaption = accountCaptionService.getByID(captionID);
//			String captionFullNo = null;// accountCaption.getCaptionFullNo();
//			String captionFullName = null;// accountCaption.getCaptionFullName();
			
			//销售发票
			AccountInvoice y = accountInvoiceService.getByID(fID);
			
			String fMasterID = null;
			String invoiceCategory = y.getInvoiceCategory();
			String invoiceCategoryLabel = y.getInvoiceCategoryLabel();
			
			String origin = y.getBillType();
			String originName = y.getBillTypeName();
			String originNo = y.getAccountInvoiceNo();
			
			BigDecimal orderAmount = y.getOrderAmountTotal();
			BigDecimal pendingAmount = y.getPendingAmount();
			BigDecimal orderAmountCleared = clearAmount;
			//BigDecimal discountCash = BigDecimal.ZERO;
			
			Date invoiceDate = y.getOrderDate();
			String invoiceCode = null;
			
			String captionID = null;
			String captionNo = null;
			String captionName = null;
			String captionFullName = null;
			
			AccountPaymentDetail accountPaymentDetail = accountPaymentDetailService.accountPaymentDetailInsert(writeOffNo, fMasterID, invoiceCategory, invoiceCategoryLabel, cashSettle, clearType, clearTypeLabel, revOpay, direction, origin, originName, originNo, invoiceDate, invoiceCode, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, orderAmount, pendingAmount, orderAmountCleared, discountCash, captionID, captionNo, captionName, captionFullName, orderNo, projectNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);

			accountPaymentDetailService.agreeIt(accountPaymentDetail,cUsercode,cUsername,userId);
			this.doItPaymentDetail(accountPaymentDetail);
			
		}
		
		//总的现金折扣金额
		if(discountCashTotal.compareTo(BigDecimal.ZERO)>0) {
			//插入折扣收款核销记录
			
			String origin = "DKHX";
			String originName = "到款核销";
			String originNo = writeOffNo;
			
			String captionID = null;
			String captionNo = null;
			String captionName = null;
			String captionFullName = null;
			
			accountPaymentDetailService.accountPaymentDetailDKHXInsert(writeOffNo, cashSettle, revOpay, direction, clearType, clearTypeLabel, billType, billTypeName, origin, originName, originNo, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, discountCashTotal, captionID, captionNo, captionName, captionFullName, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
			
		}
		
		return 0;
	}
	
	//到款核销（同时支持收款和付款）
	@Transactional
	@Override
	public JSONObject dkhx(JSONObject data, String cUsercode, String cUsername, String userId, String employeeNo, String employeeName) {
		System.out.println("dkhx.data-->>"+data.toJSONString());
		
		//String APPID = "d5c0ac391478fbbf5d85f8e28b49236f";
		String enterpriseNo = data.getString("enterpriseNo");
		String enterpriseName = data.getString("enterpriseName");
		
		// TODO Auto-generated method stub
		String customerID = data.getString("customerID");
		String writeOffNo = data.getString("writeOffNo");
		System.out.println("writeOffNo-->"+writeOffNo);
		
		BigDecimal discountCashTotal = data.getBigDecimal("discountCash");
		JSONArray rows1 = data.getJSONArray("rows1");
		JSONArray rows2 = data.getJSONArray("rows2");
		
		String orderNo = data.getString("orderNo");
		String projectNo = data.getString("projectNo");
		
		JSONObject json = new JSONObject();
		
		String dealObject = null;
		String dealObjectLabel = null;
		String customerNo = null;
		String shortName = null;
		String customerName = null;
		
//		String cUsercode = SecurityService.getCurrentPerson().getsCode();
//		String cUsername = SecurityService.getCurrentPerson().getsName();
//		String userId = SecurityService.getCurrentPerson().getsID();
//		String employeeNo = SecurityService.getCurrentPsm().getsFID();
//		String employeeName = SecurityService.getCurrentPsm().getsFName();
//		String enterpriseNo = SecurityService.getCurrentOgn().getsFID();
//		String enterpriseName =SecurityService.getCurrentOgn().getsName();
		/*
		[
            {value:0,label:'0:不送审自动审核'}
            ,{value:1,label:'1:非工作流审签'}
            ,{value:2,label:'2:自由工作流审签'}
            ,{value:3,label:'3:工作流审签'}
        ];
		*/
		
		String revOpay = data.getString("revOpay");//"I";
		
		String clearType = data.getString("clearType");//"6";
		String clearTypeLabel = data.getString("clearTypeLabel");//"6.到款核销";

		String billType = data.getString("billType");
		String billTypeName = data.getString("billTypeName");

		//检查核销批号是否存在
		/*
		List<AccountPayment> accountPayments = accountPaymentService.getByWriteOffNo(writeOffNo, enterpriseNo);
		if(accountPayments.size()>0){
			json.put("code", -1);
			json.put("status", "核销批号已经存在！");
			return json;
		}
		*/
		////////////////////////////////////////////////////////////////////////////

		if(revOpay.equals("I")) {
			FileCustomer dealObj = null;
			if(customerID!=null){
				dealObj = fileCustomerService.getByID(customerID);
			}
			
			if(dealObj!=null){
				
				dealObject = dealObj.getStorageTypeD();
				dealObjectLabel = dealObj.getStorageTypeDLabel();
				customerNo = dealObj.getCustomerNo();
				shortName = dealObj.getShortName();
				customerName = dealObj.getCustomerName();
			}
			
		}else {
			FileProvider dealObj = null;
			if(customerID!=null){
				dealObj = fileProviderService.getByID(customerID);
			}
			
			if(dealObj!=null){
				
				dealObject = dealObj.getStorageTypeD();
				dealObjectLabel = dealObj.getStorageTypeDLabel();
				customerNo = dealObj.getProviderNo();
				shortName = dealObj.getShortName();
				customerName = dealObj.getProviderName();
			}

		}
		
		int code = this.hxArrayData(writeOffNo, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, revOpay, clearType, clearTypeLabel, billType, billTypeName, discountCashTotal, rows1, rows2, orderNo, projectNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		
		json.put("code", code);
		
		return json;
	}
	
	//反到款核销
	@Transactional
	@Override
	public JSONObject fdkhx(JSONObject data) {
		// TODO Auto-generated method stub
		String writeOffNo = data.getString("writeOffNo");
		String enterpriseNo = data.getString("enterpriseNo");
		
		
		//主表（可能包含核销时产生的现金折扣记录）？？？不存在主表，全是子表
		/*
		List<AccountInvoice> accountPaymentDetails1 = accountPaymentService.getByWriteOffNo(writeOffNo, enterpriseNo);
		for(AccountInvoice accountPaymentDetail:accountPaymentDetails1){
			//反审核
			accountClosureService.unAgree(accountPaymentDetail);
			this.unDoPayment(accountPaymentDetail);
			accountClosureService.delete(accountPaymentDetail.getfID());
		}
		*/
		//子表（核销明细表）
		List<AccountPaymentDetail> accountPaymentDetails = accountPaymentDetailService.getByWriteOffNo(writeOffNo, enterpriseNo);
		for(AccountPaymentDetail accountPaymentDetail:accountPaymentDetails){
			//反审核
			accountPaymentDetailService.unAgree(accountPaymentDetail);
			this.unDoPaymentDetail(accountPaymentDetail);
			accountPaymentDetailService.delete(accountPaymentDetail.getfID());
		}
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		
		return json;
	}


	
}
